package br.com.sgi.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class RelatorioUtil {
	
	/**
	 * Prepara a tela para download de PDF.
	 * 
	 * @param context
	 * @param nomeArquivo
	 * @return
	 */
	public static HttpServletResponse preparaPaginaPdf(FacesContext context, String nomeArquivo) {
		HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
		response.setContentType("application/pdf");
		// Dispoe o relatorio para abrir ou salvar
		response.addHeader("Content-Disposition", "attachment; filename=" + nomeArquivo +".pdf");
		return response;
	}
	
	public static FacesContext getContext() {
		return FacesContext.getCurrentInstance();
	}
	
	public static JasperPrint construirRelatorio(String relatorioNome, Map<String, Object> parametros, Collection<?> listaRelatorio){
		//Preenche o dataSource com a colecao desejada
		ServletContext scontext = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
	    InputStream stream = getStreamRelatorio(relatorioNome, scontext);
		
	    if (stream instanceof BufferedInputStream) {
	        stream = (BufferedInputStream) stream;
	    } else if (stream instanceof ByteArrayInputStream) {
	        stream = (ByteArrayInputStream) stream;
	    }
		
	    JasperPrint rel = null;
		try {
			// Preenche o relatario com os parametros(Map) e a lista.
			rel = JasperFillManager.fillReport(stream, parametros,new JRBeanCollectionDataSource(listaRelatorio));
		} catch (JRException e) {
			e.printStackTrace();
		} 
		return rel;
	}
	
	private static InputStream getStreamRelatorio(String relatorioNome,
			ServletContext scontext) {
		return scontext.getResourceAsStream(System.getProperty("file.separator") + Constante.DIRETORIO_RELATORIOS + 
				System.getProperty("file.separator") + relatorioNome);
	}
	
	
	public static String getNomeRelatorioConsulta() {
		return "Relatorio" + new SimpleDateFormat("ddMMyyyy").format(new Date());
	}

}
